package top.milkbox.sys.modular.permission.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.milkbox.common.enums.CommonSortTypeEnum;
import top.milkbox.common.exceprion.CommonServiceException;
import top.milkbox.sys.modular.permission.entity.SysPermissionEntity;
import top.milkbox.sys.modular.permission.mapStruct.SysPermissionMapStruct;
import top.milkbox.sys.modular.permission.mapper.SysPermissionMapper;
import top.milkbox.sys.modular.permission.param.SysPermissionAddParam;
import top.milkbox.sys.modular.permission.param.SysPermissionEditParam;
import top.milkbox.sys.modular.permission.param.SysPermissionIdParam;
import top.milkbox.sys.modular.permission.param.SysPermissionPageParam;
import top.milkbox.sys.modular.permission.service.SysPermissionService;
import top.milkbox.sys.modular.permission.vo.SysPermissionVo;
import top.milkbox.common.utils.CommonUtil;
import top.milkbox.sys.modular.relationship.service.SysRelationshipService;

import java.util.List;

/**
 * 系统_权限表（sys_permission）服务层实现类
 *
 * @author milkbox
 * @date 2024-10-31
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermissionEntity> implements SysPermissionService {

    private SysPermissionMapper sysPermissionMapper;
    private SysRelationshipService sysRelationshipService;
    private SysPermissionMapStruct sysPermissionMapStruct;

    @Override
    public void add(SysPermissionAddParam addParam) {
        // TODO 添加权限的时候，权限码不能重复
        SysPermissionEntity entity = sysPermissionMapStruct.addParamToEntity(addParam);
        super.save(entity);
    }

    @Override
    public void delete(List<SysPermissionIdParam> paramList) {
        super.removeByIds(paramList.stream().map(SysPermissionIdParam::getId).toList());
    }

    @Override
    public void edit(SysPermissionEditParam editParam) {
        findEntity(editParam.getId());
        SysPermissionEntity entity = sysPermissionMapStruct.editParamToEntity(editParam);
        super.updateById(entity);
    }

    @Override
    public SysPermissionVo detail(SysPermissionIdParam idParam) {
        SysPermissionEntity entity = findEntity(idParam.getId());
        SysPermissionVo vo = sysPermissionMapStruct.entityToVo(entity);
        // 此处进行数据翻译操作，，根据不同的业务逻辑将entity对象转为vo对象......

        return vo;
    }

    @Override
    public SysPermissionEntity findEntity(Integer entityId) {
        SysPermissionEntity entity = super.getById(entityId);
        if (ObjectUtil.isEmpty(entity)) {
            throw new CommonServiceException("实体未找到（{}）", entityId);
        }
        return entity;
    }

    @Override
    public Page<SysPermissionVo> page(SysPermissionPageParam pageParam) {
        QueryWrapper<SysPermissionEntity> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(pageParam.getSearchKey())) {
            queryWrapper.lambda().like(SysPermissionEntity::getName, pageParam.getSearchKey())
                    .or().like(SysPermissionEntity::getValue, pageParam.getSearchKey());
        } else if (ObjectUtil.isAllNotEmpty(pageParam.getSortField(), pageParam.getSortType())) {
            queryWrapper.orderBy(true,
                    pageParam.getSortType() == CommonSortTypeEnum.ASC,
                    StrUtil.toUnderlineCase(pageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(SysPermissionEntity::getSortCode);
        }
        queryWrapper.lambda().orderByAsc(SysPermissionEntity::getId);

        Page<SysPermissionEntity> entityPage = super.page(pageParam.toBaomidouPage(), queryWrapper);
        // 此处进行远程调用或关联查询......

        Page<SysPermissionVo> voPage = CommonUtil.convertPage(entityPage, entity -> {
            SysPermissionVo vo = sysPermissionMapStruct.entityToVo(entity);
            // 此处进行数据翻译操作，根据不同的业务逻辑将entity对象转为vo对象......

            return vo;
        });
        return voPage;
    }

    @Override
    public List<SysPermissionEntity> listByLoginUser() {
        // 获取指定用户关联的权限id集合，以及其所属角色关联的权限id集合
        List<Integer> permissionIdList = sysRelationshipService.findAllPermissionIdListByUserId(StpUtil.getLoginIdAsInt());
        // 根据id集合查询权限表
        return super.list(new LambdaQueryWrapper<SysPermissionEntity>().in(SysPermissionEntity::getId, permissionIdList));
    }

    @Override
    public SysPermissionVo getByValue(String value) {
        SysPermissionEntity entity = super.getOne(
                new LambdaQueryWrapper<SysPermissionEntity>().eq(SysPermissionEntity::getValue, value));
        if (ObjectUtil.isEmpty(entity)) {
            return null;
        }
        return sysPermissionMapStruct.entityToVo(entity);
    }

}